package com.teamizer.client;

import java.util.ArrayList;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Teamizer implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);
	
	private DialogBox dialogBox = null;
	
	private DialogBox advertisementDialogBox = null;
	
	private Button sendButton = null;

	private Button closeButton;

	private Panel resultPanel;

	private Panel advertisementPanel; 

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		// All visual components are created

		VerticalPanel mainPanel = getMainPanel();

		HorizontalPanel teamsPanel = new HorizontalPanel();
		teamsPanel.setSpacing(20);
		HorizontalPanel playersPanel = new HorizontalPanel();
		playersPanel.setSpacing(20);
		HorizontalPanel buttonsPanel = new HorizontalPanel();
		buttonsPanel.setSpacing(20);
		buttonsPanel.addStyleName("buttonsPanel");

		mainPanel.add(teamsPanel);
		mainPanel.add(playersPanel);
		mainPanel.add(buttonsPanel);

		final ListBox color1 = new ListBox(false);
		color1.addItem("White");
		color1.addItem("Black");
		color1.addItem("Yellow");
		color1.addItem("Green");
		color1.addItem("Melon");
		color1.addItem("Purple");
		color1.addItem("Tooth white");
		color1.addItem("Broken white");
		color1.addItem("Bottle green");
		color1.addItem("Watermelon");

		final ListBox color2 = new ListBox(false);
		color2.addItem("Black");
		color2.addItem("White");
		color2.addItem("Yellow");
		color2.addItem("Green");
		color2.addItem("Melon");
		color2.addItem("Purple");
		color2.addItem("Tooth white");
		color2.addItem("Broken white");
		color2.addItem("Bottle green");
		color2.addItem("Watermelon");
		
		final Label teams = new Label("Choose teams colors");
		
		teamsPanel.add(teams);
		teamsPanel.add(color1);
		teamsPanel.add(color2);
		

		final TextBox nameField = new TextBox();
		nameField.setText("");
		// Focus the cursor on the name field when the app loads
		nameField.selectAll();

		// Add a list box with multiple selection enabled
		final ListBox multiBox = new ListBox(true);
		multiBox.ensureDebugId("cwListBox-multiBox");
		multiBox.setWidth("11em");
		multiBox.setVisibleItemCount(10);
		VerticalPanel multiBoxPanel = new VerticalPanel();
		multiBoxPanel.setSpacing(4);
		multiBoxPanel.add(multiBox);

		final Button addPlayer = new Button("Add player");
		// We can add style names to widgets
		addPlayer.addStyleName("addPlayer");
		// Add a handler to close the DialogBox
		class AddPlayerHandler implements ClickHandler, KeyUpHandler {
			public void onClick(ClickEvent event) {
				String playerName = nameField.getText();
				if (playerName.length() > 0) {
					multiBox.addItem(playerName);
					nameField.setText("");
				}
			}

			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					String playerName = nameField.getText();
					if (playerName.length() > 0) {
						multiBox.addItem(playerName);
						nameField.setText("");
					}
				}
			}
		}
		AddPlayerHandler addPlayerHandler = new AddPlayerHandler();
		addPlayer.addClickHandler(addPlayerHandler);

		final Button remPlayer = new Button("Remove player");
		// We can add style names to widgets
		remPlayer.addStyleName("addPlayer");
		// Add a handler to close the DialogBox
		class RemPlayerHandler implements ClickHandler {
			public void onClick(ClickEvent event) {
				int selected = multiBox.getSelectedIndex();
				if (selected >= 0) {
					multiBox.removeItem(selected);
				}
			}
		}
		RemPlayerHandler remPlayerHandler = new RemPlayerHandler();
		remPlayer.addClickHandler(remPlayerHandler);
		
		playersPanel.add(nameField);
//		playersPanel.add(addPlayer);
		playersPanel.add(remPlayer);
		playersPanel.add(multiBox);
		buttonsPanel.add(getSendButton());

		RootPanel.get("mainPanel").add(mainPanel);

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				showAnnounce();
			}
			
			private void showAnnounce() {
				greetingService.getAnnounce(new AsyncCallback<String>() {
					@Override
					public void onFailure(Throwable caught) {

					}
					@Override
					public void onSuccess(String result) {
						getAdvertisementDialogBox().setText("Advertisement");
						getAdvertisePanel().clear();
						getAdvertisePanel().add(new Image(result));
						getAdvertisementDialogBox().center();
						getAdvertisementDialogBox().show();
						sendTeamsToServer();
					}
				});
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void sendTeamsToServer() {
				getSendButton().setEnabled(false);

				ArrayList<String> players = new ArrayList<String>();
				for (int i = 0; i < multiBox.getItemCount(); i++) {
					players.add(multiBox.getItemText(i));
				}

				ArrayList<String> teams = new ArrayList<String>();
				teams.add(color1.getItemText(color1.getSelectedIndex()));
				teams.add(color2.getItemText(color2.getSelectedIndex()));
				greetingService.teamizePlayers(players, teams,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								getAdvertisementDialogBox().hide();

								getResultPanel().clear();
								getResultPanel().add(new HTML(SERVER_ERROR));
								getResultPanel().add(getCloseButton());

								getCloseButton().setFocus(true);

								getDialogBox().setText("Remote Procedure Call - Failure");
								getDialogBox().center();
								getDialogBox().show();
							}

							public void onSuccess(String result) {
								getAdvertisementDialogBox().hide();

								getResultPanel().clear();
								getResultPanel().add(new HTML(result));

								getCloseButton().setFocus(true);

								getDialogBox().setText("Teamizer Randomly teams proposal");
								getDialogBox().center();
								getDialogBox().show();
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(addPlayerHandler);
		nameField.setFocus(true);

	}
	
	private DialogBox getDialogBox() {
		// Create the popup dialog box
		if (dialogBox == null) {
			dialogBox = new DialogBox();
			dialogBox.setAnimationEnabled(true);
			dialogBox.setGlassEnabled(true);

			VerticalPanel dialogVPanel = new VerticalPanel();
			dialogVPanel.addStyleName("dialogVPanel");
			dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);

			dialogVPanel.add(getResultPanel());
			dialogVPanel.add(getCloseButton());
			dialogBox.setWidget(dialogVPanel);
		}

		return dialogBox;
	}
	
	private DialogBox getAdvertisementDialogBox() {
		// Create the popup dialog box
		if (advertisementDialogBox == null) {
			advertisementDialogBox = new DialogBox();
			advertisementDialogBox.setAnimationEnabled(true);
			advertisementDialogBox.setGlassEnabled(true);

			VerticalPanel dialogVPanel = new VerticalPanel();
			dialogVPanel.addStyleName("dialogVPanel");
			dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);

			dialogVPanel.add(getAdvertisePanel());
			advertisementDialogBox.setWidget(dialogVPanel);
		}

		return advertisementDialogBox;
	}
	
	private Panel getAdvertisePanel() {
		if (advertisementPanel == null) {
			advertisementPanel = new VerticalPanel();
		}
		return advertisementPanel;
	}

	private Panel getResultPanel() {
		if (resultPanel == null) {
			resultPanel = new HorizontalPanel();
		}
		return resultPanel;
	}
	
	private Button getSendButton() {
		if (sendButton == null) {
			sendButton = new Button("Teamize");
			sendButton.addStyleName("sendButton");
		}
		return sendButton;
	}
	
	private Button getCloseButton() {
		if (closeButton == null) {
			closeButton = new Button("Close");
			closeButton.getElement().setId("closeButton");
			closeButton.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					getDialogBox().hide();
					getSendButton().setEnabled(true);
					getSendButton().setFocus(true);
				}
			});

		}
		return closeButton;
	}

	private VerticalPanel getMainPanel() {
		VerticalPanel vPanel = new VerticalPanel();
		return vPanel;
	}
}
